package com.zhongsou.souyue.filemanager;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2015/6/11.
 */
public class WriteCrashHandler {
    private Handler mSaveStoreHandler;//自定义handler
    public static final int OPEAN_WRITER = 0;//打开writer标识
    public static final int WRITE_FILELOG = 1;//写日志
    private Writer mWriter;//写日志的流
    private String mFileName;
    private File currentFile;
    private static final int MAX_SIZE = 1024 * 100;//记录日志文件最大size

    public WriteCrashHandler(String saveFileName) {
        if (saveFileName == null) {
            this.mFileName = DateString() + ".crash";
        } else {
            this.mFileName = saveFileName;
        }

        if (!MBaseThread.handlerThread.isAlive()) {
            MBaseThread.handlerThread.start();
        }
        mSaveStoreHandler = new Handler(MBaseThread.handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case OPEAN_WRITER:
                        try {
                            closeWriter();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            openWriter();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case WRITE_FILELOG:
                        String crashLog = (String) msg.obj;
                        try {
                            if (mWriter == null) {
                                openWriter();
                                Log.i("WriteCrashHandler", "打开Writer流");
                            }
                            if (mWriter != null) {
                                mWriter.append(crashLog);
                                mWriter.flush();
                                Log.i("WriteCrashHandler", "写入文件成功");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            mSaveStoreHandler.sendEmptyMessage(OPEAN_WRITER);
                        }
                        verifyCrashFileSize();//检测文件大小
                        break;
                }
            }
        };
        mSaveStoreHandler.sendEmptyMessage(OPEAN_WRITER);
    }

    private void closeWriter() {
        try {
            if (mWriter != null) {
                mWriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void openWriter() {
        if (mFileName != null) {
            String filePath = FileUtils.crashDir + mFileName;
            Log.i("WriteCrashHandler", "打开crashHandler 地址为："+filePath);
            if (FileUtils.ifExistFile(filePath)) {//文件及其目录存在
            } else {//创建文件及其目录
                new File(filePath).getParentFile().mkdirs();
                try {
                    currentFile = new File(filePath);
                    currentFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.i("WriteCrashHandler", " 创建文件失败", e);
                }
            }
            try {
                if (mWriter == null) {
                    mWriter = new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            Log.i("WriteCrashHandler", "mFileName 不能为 null");
        }
    }

    public void saveLog(String logStr) {
        Message msg = new Message();
        msg.obj = logStr;
        msg.what = WRITE_FILELOG;
        mSaveStoreHandler.sendMessage(msg);
    }

    private void verifyCrashFileSize() {
        if (currentFile != null) {
            if (currentFile.length() > MAX_SIZE) {//如果日志文件超过最大size则以后写入到另外的文件中
                mFileName = DateString() + ".crash";
                closeWriter();
                openWriter();
            }
        }
    }

    private String DateString() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return format.format(new Date());
    }
}
